package com.wz.wzbubbleai.service;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import com.wz.wzbubbleai.utils.LogUtil;
import com.wz.wzbubbleai.view.MainView;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by wangbin on 18-1-10.
 */
public class FloatWindowService extends Service {

    public final static int SHOW_WINDOW = 10001;
    public final static int CANCEL_WINDOW = 10002;

    /**
     * 用于在线程中创建或移除悬浮窗。
     */
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case FloatWindowService.SHOW_WINDOW:{
                    if(!MainView.isWindowShowing()){
                        LogUtil.d("FloatWindowService.SHOW_WINDOW");
                        MainView mainView = new MainView();
                        mainView.showPopupWindow(getApplicationContext());
                    }
                }
                break;
                case FloatWindowService.CANCEL_WINDOW:{
                    if(MainView.isWindowShowing()){
                        MainView.hidePopupWindow();
                    }
                }
            }
        }
    };

    /**
     * 定时器，定时进行检测当前应该创建还是移除最顶层
     */
    private Timer timer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.d("onStartCommand");
        Message message = handler.obtainMessage();
        message.what = SHOW_WINDOW;
        handler.sendMessage(message);
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Service被终止的同时也停止定时器继续运行
        timer.cancel();
        timer = null;
    }

    class RefreshTask extends TimerTask {

        @Override
        public void run() {
            if (!MainView.isWindowShowing()) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        //MainView.showPopupWindow(getApplicationContext());
                    }
                });
            }
        }
    }
}